from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.orders import OrderInfoSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo


class OrdersView(ModelViewSet):
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定序列化器
    serializer_class = OrderInfoSerializer
    # 指定分页器
    pagination_class = PageNum
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)

    # 在视图中定义status方法修改订单状态
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error': '订单不存在'}, status=400)
        # 修改订单状态
        status = request.data.get('status')
        order.status = status
        order.save()
        # 返回结果
        ser = self.get_serializer(order)
        return Response({
            'order_id': order.order_id,
            'status': status

        })
